#coding=utf-8
import json

import pymysql
import random
import time
from datetime import datetime
import threading

from mysql.connector import cursor

# MySQL数据库连接

# 数据库配置
config = {
    'host': '192.168.1.100',
    'user': 'tester',
    'password': 'tester1234',
    'database': 'gwza_hardware',
    'charset': 'utf8mb4',
}


# 定义数据更新函数
def update_data(thread_id, ids):

    try:
        conn = pymysql.connect(**config)
        cursor = conn.cursor()
        num = 5

        while num>0:
            for id in ids:
                print(id)
            #获取当前记录的x, y, z, update_time
                # cursor.execute(f"SELECT x,y,z,update_time FROM map_device WHERE device_id ='{id}'")
                # x, y, z, update_time = cursor.fetchone()
                x1 = 6378
                y1 = 20500
                z1 = 13500

                # 随机变动x和y的值（范围是正负40）
                x_new = x1 + random.uniform(-400, 400)
                y_new = y1 + random.uniform(-400, 400)

                # 随机变动z的值（范围是正负1）
                z_new = z1 + random.uniform(-1000, 1000)

                # 更新update_time为当前时间
                update_time_new = datetime.now()

                #更新memo

                pa = 10000
                pa_new = pa + random.uniform(-1000, 1000)
                pa = str(pa_new)
                # 原始 JSON 字符串
                memo = '{"label": "489617 5411", "pa": "old_value", "elect": "43"}'

                # 将 pa_new 插入到 JSON 字符串中的 "pa" 键
                memo_dict = json.loads(memo)  # 将 JSON 字符串转换为字典
                memo_dict['pa'] = pa  # 更新 "pa" 键的值
                memo_updated = json.dumps(memo_dict)  # 将更新后的字典转换回 JSON 字符串

                #加anchors
                anchors = '{"total": 1, "time": "2024-09-04 17:00:32", "anchors": [{"id": "GW2846", "dis": 4000}, ]}'
                anchors_updated = json.dumps(anchors)
                # 更新数据库中的数据
                cursor.execute(f"UPDATE map_device SET device_status=1,x={x_new}, y={y_new}, z={z_new}, update_time='{update_time_new}',anchors='{anchors_updated}',memo='{memo_updated}' WHERE device_id = '{id}'")
                conn.commit()

            # 等待一秒钟
            time.sleep(1)
            num = num -1

    except KeyboardInterrupt:
        print(f"Thread {thread_id} interrupted by user, stopping data updates.")


    # except Exception as e:
    #     print(f"Error in thread {thread_id}: {e}")

    finally:
        if 'cursor' in locals():
            cursor.close()
        if 'conn' in locals():
            conn.close()

try:
 #创建线程数
    num_threads = 1

    # 查询A表中所有数据的id
    # conn = pymysql.connect(host,user,password,db,port,charset='utf8mb4')

    conn = pymysql.connect(**config)
    cursor = conn.cursor()
    cursor.execute("SELECT device_id FROM map_device where device_type=1;")
    ids = [row[0] for row in cursor.fetchall()]
    ids = ['GW5411']

    # 划分数据，每个线程处理部分数据
    thread_ids = range(num_threads)  #rang(0,numthreads)
    chunk_size = len(ids) // num_threads
    chunks = [ids[i:i + chunk_size] for i in range(0, len(ids), chunk_size)]

    # 创建并启动线程
    threads = []
    for thread_id, chunk in zip(thread_ids, chunks):
        thread = threading.Thread(target=update_data, args=(thread_id, chunk))
        thread.start()
        threads.append(thread)

    # 等待所有线程完成
    for thread in threads:
        thread.join()

except Exception as e:
    print(f"Error connecting to MySQL: {e}")

finally:
    if 'cursor' in locals():
        cursor.close()
    if 'conn' in locals():
        conn.close()
